package merlin.servlets;

import java.io.IOException;
import java.text.ParseException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import merlin.beans.CustomerDetailsBean;
import merlin.dao.DbResultSet;
import merlin.managers.BibServiceManager;
import merlin.managers.ReportTitlesManager;

public class BIBServiceServlet extends HttpServlet {

	// Page name constants
	private final String LOGIN_PAGE = "bibIndustryWatchLogin.jsp";
	private final String MAIN_PAGE = "bibMainPage.jsp";
	
	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		doPost(request,response);
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		try{
			System.out.println(">>>>>>>>>>>>>>>>");
			String mode = request.getParameter("mode");
			
			System.out.println(new java.util.Date().toLocaleString() + " : mode : " + mode);
			if(mode==null || mode.equals("")){
				dispatch(request,response,LOGIN_PAGE,true);
				return;
			};
			
			if("login".equals(mode)){
				handleLogin(request, response);
			}
			
			
		}catch(Exception e){
			System.out.println("CAUGHT");
			e.printStackTrace();
			request.setAttribute("javax.servlet.jsp.jspException",e); //the exception implicit JSP object.
			dispatch(request,response,"/mr_errhandler.jsp",false);
		}finally{
			System.out.println("<<<<<<<<<<<<<<<");
		}
	}
	
	protected void handleLogin(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException,ParseException{
		String uid = request.getParameter("txtEmailAddress");
		String pwd = request.getParameter("txtPassword");

		String nextView=null;
		if(uid == null || uid.length() == 0){
			// insufficient information.
			request.setAttribute("error.login","Incorrect Details Entered");
			nextView = LOGIN_PAGE;
		}else{
			uid = uid.toLowerCase().trim();
			pwd = pwd.toLowerCase();
			CustomerDetailsBean bean = BibServiceManager.login(uid, pwd);
			if(bean == null){
				// login has failed
				request.setAttribute("error.login","Invalid email ID");
				nextView = LOGIN_PAGE;
			}else{
				HttpSession session = request.getSession(true);
				session.setAttribute("username",uid);
				session.setAttribute("reportId",String.valueOf(bean.getReportTitlesId()));
				session.setAttribute("reportTitle",bean.getReportTitle());
				session.setAttribute("userDetails", bean);
				// Get the reports for this user.
				String reportIds = String.valueOf(bean.getReportTitlesId());
				if(bean.getAdditionalReportNumbers() != null){
					reportIds += bean.getAdditionalReportNumbers().replace('/',',');
				}
	
				DbResultSet reportsForUser = ReportTitlesManager.selectReportTitlesRecords("REPORT_TITLES_ID in(" + reportIds + ")"," REPORT_TITLE ASC");
				session.setAttribute("reportsForUser", reportsForUser);
				nextView = MAIN_PAGE;
			}
			
		}
		dispatch(request,response,nextView,true);
	}

	
	
	/**
	 * Forwards/redirects the request to the requested resource.
	 */
	protected void dispatch(HttpServletRequest request,HttpServletResponse response,String page,boolean redirect) throws ServletException,IOException{
		if(redirect){
			System.out.println("redirecting to " + page);
			response.sendRedirect(page);
		}else{
			System.out.println("forwarding to " + page);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
			dispatcher.forward(request, response);
		}
	}
}
